package com.restaurant.application.indexes.couponmanagelist;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.nebutown.base.ViewSpec;
import com.nebutown.base.data.View;
import com.nebutown.base.data.ViewUpdate;
import com.nebutown.commonunits.dataface.DataModes;
import com.nebutown.commonunits.dataface.EntryTypes;
import com.nebutown.commonunits.dataface.FormShell;
import com.nebutown.commonunits.dataface.TableShell;
import com.nebutown.commonunits.dataface.definitions.*;
import com.nebutown.commonunits.uidataface.UIDataFace;
import com.nebutown.commonunits.utils.DateTimeUtils;
import com.nebutown.generation.basictype.UID;
import com.restaurant.application.couponmanage.CouponManage;
import com.restaurant.application.couponmanage.support.CouponManageData;
import com.restaurant.application.couponmanagecl.CouponManageCL;
import com.restaurant.application.couponmanagecs.CouponManageCS;
import com.restaurant.application.indexes.couponmanagelist.mysql.CouponManageListBean;
import com.restaurant.application.indexes.couponmanagelist.mysql.CouponManageListCriteria;
import com.restaurant.application.indexes.couponmanagelist.mysql.CouponManageListImpl;
import com.restaurant.application.indexes.couponmanagelist.support.AbstractAssistCouponManageList;
import com.restaurant.application.indexes.couponmanagelist.support.DeleteData;
import com.restaurant.application.minifacade.data.CardBO;
import com.restaurant.application.util.CommonUtils;

import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 */
public class AssistCouponManageListImpl extends AbstractAssistCouponManageList {
    @Override
    public View getFullView() {
        return newCommonTable(new CouponManageListCriteria());
    }

    @Override
    public View getViewLead(ViewSpec viewSpec) {
        return newCommonTable(new CouponManageListCriteria());
    }

    @Override
    public ViewUpdate delete(DeleteData delete, int[] seq) {
        if (Objects.nonNull(delete) && delete.getIdList().size() > 0) {
            List<Long> recordIdList = Lists.newArrayList();
            delete.getIdList().forEach(e -> {
                List<CouponManageListBean> beans = getIndex(CouponManageListImpl.class).search(new CouponManageListCriteria().withIdEquals(e.getId()), null, 1);
                CouponManageData data = new CouponManageData().withState(CouponManage.STATE_DELETE);
                if (beans.size() > 0) {
                    recordIdList.add(beans.get(0).getRecordId());
                    CouponManageListBean bean = beans.get(0);
                    if (CouponManage.TYPE_REBATE.equals(bean.getType())) {
                        getUnit(CouponManageCS.class, bean.getCouponManageUid()).modify(data);
                    } else if (CouponManage.TYPE_MINUS.equals(bean.getType())) {
                        getUnit(CouponManageCL.class, bean.getCouponManageUid()).modify(data);
                    } else if (CouponManage.TYPE_GIVE.equals(bean.getType())) {
                        getUnit(CouponManage.class, bean.getCouponManageUid()).modify(data);
                    }
                }
            });
            if (recordIdList.size() > 0) {
                getIndex(CouponManageListImpl.class).delete(recordIdList);
            }
        }
        return returnView(getFullView());
    }

    @Override
    public ViewUpdate search(CouponManageListCriteria search, int[] seq) {
        return returnView(newCommonTable(search));
    }

    @Override
    public ViewUpdate modify(int[] seq) {
        return getCouponManageView(seq[0]);
    }

    @Override
    public ViewUpdate crateCD(int[] seq) {
        UID uid = createNode(CouponManage.class.getName()).getId();
        return returnPushInContainer(uid, false);
    }

    @Override
    public ViewUpdate crateCS(int[] seq) {
        UID uid = createNode(CouponManageCS.class.getName()).getId();
        return returnPushInContainer(uid, false);
    }

    @Override
    public ViewUpdate crateCL(int[] seq) {
        UID uid = createNode(CouponManageCL.class.getName()).getId();
        return returnPushInContainer(uid, false);
    }

    private ViewUpdate getCouponManageView(long recordId) {
        List<CouponManageListBean> beans = getIndex(CouponManageListImpl.class).search(new CouponManageListCriteria().withRecordId(recordId), null, 1);
        if (beans.size() > 0) {
            CouponManageListBean bean = beans.get(0);
            return returnPushInContainer(bean.getCouponManageUid(), false);
        }
        return returnView(getFullView());
    }

    @Override
    public List<CardBO> getAllNormal() {
        List<CouponManageListBean> beans = getIndex(CouponManageListImpl.class)
                .search(new CouponManageListCriteria().withStateEquals(CouponManage.STATE_VALID), null, 100000);
        List<CardBO> dataList = Lists.newArrayList();
        if (beans.size() > 0) {
            beans.forEach(e -> dataList.add(getCardBO(e)));
        }
        return dataList;
    }

    private CardBO getCardBO(CouponManageListBean bean) {
        return new CardBO()
                .withCardId(bean.getNumber())
                .withContent(bean.getModality())
                .withEndTime(DateTimeUtils.toTime(bean.getEndTime()))
                .withRemark(bean.getRemarks());
    }

    private View newCommonTable(CouponManageListCriteria criteria) {
        List<CouponManageListBean> beans = getIndex(CouponManageListImpl.class).search(criteria, null, 0, 20);
        int totalRecord = getIndex(CouponManageListImpl.class).count(criteria);
        PageInfo info = CommonUtils.getPageInfo(1, 20, totalRecord);
        PageForm pageForm = newFormShell(criteria, beans, info).getForm();
        return getSingleton(UIDataFace.class).newGenericForm(unitPosition(), pageForm);
    }

    private FormShell newFormShell(CouponManageListCriteria criteria, List<CouponManageListBean> beans, PageInfo info) {
        FormShell shell = new FormShell("优惠券/优惠券管理", 3, 3);

        shell.source(criteria, DataModes.EDIT);
        shell.at(0, 0, "优惠券ID")
                .getEntry(CouponManageListCriteria.FN_NUMBERLIKE, criteria.getNumberLike())
                .placeHolder("优惠券ID")
                .simpleEntry(EntryTypes.STRING)
                .getContent().setEditable(true);
        shell.at(0, 1, "券名")
                .getEntry(CouponManageListCriteria.FN_MODALITYLIKE, criteria.getModalityLike())
                .placeHolder("券名")
                .simpleEntry(EntryTypes.STRING)
                .getContent().setEditable(true);
        shell.at(0, 2, "状态")
                .getEntry(CouponManageListCriteria.FN_STATEEQUALS, criteria.getStateEquals())
                .placeHolder("状态")
                .selectFrom(CouponManage.STATE_VALID, CouponManage.STATE_INVALID)
                .getContent().setEditable(true);
        shell.at(0, 3, "类型")
                .getEntry(CouponManageListCriteria.FN_TYPEEQUALS, criteria.getTypeEquals())
                .placeHolder("类型")
                .selectFrom(CouponManage.TYPE_GIVE, CouponManage.TYPE_MINUS, CouponManage.TYPE_REBATE)
                .getContent().setEditable(true);

        shell.at(1, 0, "查询")
                .buttonField(getPath(CMD_SEARCH), "", true);
        shell.at(1, 1, "创建-代金券")
                .buttonField(getPath(CMD_CRATECD), "", true);
        shell.at(1, 2, "创建-折扣券")
                .buttonField(getPath(CMD_CRATECS), "", true);
        shell.at(1, 3, "创建-满减券")
                .buttonField(getPath(CMD_CRATECL), "", true);
        shell.at(2, 0, "删除")
                .buttonField(getPath(CMD_DELETE), "", true);

        TableShell tableShell = new TableShell<>(CouponManageListBean.class, beans).withPageInfo(info);
        tableShell.createColumn(CouponManageListBean.FN_NUMBER).withName("优惠券ID").cellCalculator(e -> {
            CouponManageListBean bean = (CouponManageListBean) e;
            return new CellData().withField(new FieldContent().withSimpleField(bean.getNumber()));
        });
        tableShell.createColumn(CouponManageListBean.FN_TYPE).withName("类型").cellCalculator(e -> {
            CouponManageListBean bean = (CouponManageListBean) e;
            return new CellData().withField(new FieldContent().withSimpleField(bean.getType()));
        });
        tableShell.createColumn(CouponManageListBean.FN_MODALITY).withName("券名").cellCalculator(e -> {
            CouponManageListBean bean = (CouponManageListBean) e;
            return new CellData().withField(new FieldContent().withSimpleField(bean.getModality()));
        });
        tableShell.createColumn(CouponManageListBean.FN_CREATETIME).withName("有效期").cellCalculator(e -> {
            CouponManageListBean bean = (CouponManageListBean) e;
            return new CellData().withField(new FieldContent().withSimpleField(DateTimeUtils.toTime(bean.getReceiveTime()) + "-" + DateTimeUtils.toTime(bean.getEndTime())));
        });
        tableShell.createColumn(CouponManageListBean.FN_SHOPNAME).withName("适用门店").cellCalculator(e -> {
            CouponManageListBean bean = (CouponManageListBean) e;
            return new CellData().withField(new FieldContent().withSimpleField(bean.getShopName()));
        });
        tableShell.createColumn(CouponManageListBean.FN_STATE).withName("状态").cellCalculator(e -> {
            CouponManageListBean bean = (CouponManageListBean) e;
            return new CellData().withField(new FieldContent().withSimpleField(bean.getState()));
        });
        tableShell.createColumn(CouponManageListBean.FN_LIMITID).withName("领用限制").cellCalculator(e -> {
            CouponManageListBean bean = (CouponManageListBean) e;
            return new CellData().withField(new FieldContent().withSimpleField("每个用户仅限领" + bean.getLimitId() + "张；" + "每个账户内仅限" + bean.getLimitAccount() + "张"));
        });
        tableShell.createColumn(CouponManageListBean.FN_TOTALAMOUNT).withName("发行量").cellCalculator(e -> {
            CouponManageListBean bean = (CouponManageListBean) e;
            return new CellData().withField(new FieldContent().withSimpleField(bean.getTotalAmount()));
        });
        tableShell.createColumn(CouponManageListBean.FN_AMOUNT).withName("已领取").cellCalculator(e -> {
            CouponManageListBean bean = (CouponManageListBean) e;
            return new CellData().withField(new FieldContent().withSimpleField(bean.getAmount()));
        });
        tableShell.createColumn("编辑").withName("编辑").cellCalculator(e -> {
            CouponManageListBean bean = (CouponManageListBean) e;
            return new CellData()
                    .withField(new FieldContent().withButton(new ButtonField().withLabel("编辑").withButtonPath(getPath(CMD_MODIFY, bean.getRecordId()))));
        });

        shell.at(3, 0, "优惠券/优惠券管理")
                .large(4, 1)
                .getEntry("error", "")
                .tableEntry(tableShell);
        return shell;
    }

    @Override
    public CouponManageListBean createBean(UID uid, CouponManageData data) {
        if (Objects.isNull(uid) || Objects.isNull(data)) {
            return null;
        }
        return new CouponManageListBean()
                .withCouponManageUid(uid)
                .withId(data.getId())
                .withNumber(data.getNumber())
                .withCreateTime(data.getCreateTime())
                .withModifyTime(data.getModifyTime())
                .withReceiveTime(data.getReceiveTime())
                .withEndTime(data.getEndTime())
                .withType(data.getType())
                .withModality(data.getModality())
                .withFullMoney(data.getFullMoney())
                .withMinusMoney(data.getMinusMoney())
                .withShopUid(data.getShopUid().value())
                .withShopName(data.getShopName())
                .withRemarks(data.getRemarks())
                .withTotalAmount(String.valueOf(data.getTotalAmount()))
                .withAmount(String.valueOf(data.getAmount()))
                .withState(data.getState())
                .withLimitId(String.valueOf(data.getLimitId()))
                .withLimitAccount(String.valueOf(data.getLimitAccount()));
    }

    @Override
    public CouponManageListBean updateBean(UID uid, CouponManageData data, CouponManageListBean bean) {
        if (Objects.isNull(uid) || Objects.isNull(data) || Objects.isNull(bean)) {
            return null;
        } else {
            bean.withCouponManageUid(uid);
        }

        if (Objects.nonNull(data.getEndTime())) {
            bean.withEndTime(data.getEndTime());
        }
        if (Objects.nonNull(data.getReceiveTime())) {
            bean.withReceiveTime(data.getReceiveTime());
        }
        if (Objects.nonNull(data.getFullMoney()) && data.getFullMoney() > 0) {
            bean.withFullMoney(data.getFullMoney());
        }
        if (!Strings.isNullOrEmpty(data.getModality())) {
            bean.withModality(data.getModality());
        }
        if (!Strings.isNullOrEmpty(data.getType())) {
            bean.withType(data.getType());
        }
        if (Objects.nonNull(data.getModifyTime())) {
            bean.withModifyTime(data.getModifyTime());
        }
        if (Objects.nonNull(data.getMinusMoney()) && data.getMinusMoney() > 0) {
            bean.withMinusMoney(data.getMinusMoney());
        }
        if (!Strings.isNullOrEmpty(data.getShopName())) {
            bean.withShopName(data.getShopName());
        }
        if (Objects.nonNull(data.getShopUid())) {
            bean.withShopUid(data.getShopUid().value());
        }
        if (Objects.nonNull(data.getTotalAmount())) {
            bean.withTotalAmount(String.valueOf(data.getTotalAmount()));
        }
        if (Objects.nonNull(data.getAmount())) {
            bean.withAmount(String.valueOf(data.getAmount()));
        }
        if (!Strings.isNullOrEmpty(data.getRemarks())) {
            bean.withRemarks(data.getRemarks());
        }
        if (!Strings.isNullOrEmpty(data.getState())) {
            bean.withState(data.getState());
        }
        if (Objects.nonNull(data.getLimitId()) && data.getLimitId() > 0) {
            bean.withLimitId(String.valueOf(data.getLimitId()));
        }
        if (Objects.nonNull(data.getLimitAccount()) && data.getLimitAccount() > 0) {
            bean.withLimitAccount(String.valueOf(data.getLimitAccount()));
        }
        return bean;
    }
}
